package com.example.barry.pdf;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.example.barry.pdf.Net.GetProjectAsynTask;
import com.example.barry.pdf.Net.GetStationAsynTask;
import com.example.barry.pdf.Net.GetUnitIdAsynTask;
import com.example.barry.pdf.Utils.Help;

import java.util.ArrayList;

import java.util.List;
import java.util.Map;



public class MainActivity extends Activity {

    private EditText portalHost, plantCode, local;
    private Button go ;
    private Spinner project , station ,unitId , work;
    private  List<Map<String,Object>> projectlists=new ArrayList<Map<String,Object>>();
    private List<Map<String,Object>> stationlists = new ArrayList<Map<String, Object>>();
    private List<Map<String,Object>> unitIdlists = new ArrayList<Map<String, Object>>();
    private SimpleAdapter projectAdapter , stationAdapter , unitIdAdapter;
    private MyApplication myApplication;
    private Help help = new Help();
    private ProgressDialog progressDialog;
    private LinearLayout PortalHost, PlantCode,Project,Station,UnitID;

    Handler projectHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case  0x123:
                    closeProgressDialog();
                    projectlists= (List<Map<String, Object>>) msg.obj;
                    if (projectlists.size() == 0){
                        Toast.makeText(MainActivity.this,"Sorry, I can't find anything",Toast.LENGTH_LONG).show();
                    }else {
                        projectAdapter = new SimpleAdapter(MainActivity.this,projectlists,R.layout.project_item,new String[]{"siteName","siteCommunityId"},new int[]{R.id.siteName,R.id.siteCommunityId});
                        project.setAdapter(projectAdapter);
                    }
                    break;
                default:
                    break;
            }
        }
    };
    Handler stationHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x123:
                    closeProgressDialog();
                    stationlists = (List<Map<String,Object>>) msg.obj;
                    if (stationlists.size() == 0){
                        Toast.makeText(MainActivity.this,"Sorry, I can't find anything",Toast.LENGTH_LONG).show();
                        unitIdlists.clear();
                        unitIdAdapter.notifyDataSetChanged();
                    }
                        stationAdapter = new SimpleAdapter(MainActivity.this, stationlists, R.layout.station_item, new String[]{"sfdcser_name", "sfdcser_Id", "clientname", "serverid"}, new int[]{R.id.sfdcserName, R.id.sfdcserId, R.id.clientName, R.id.serverid});
                        station.setAdapter(stationAdapter);
                        //unitIdlists.clear();

                    break;
                default:
                    break;
            }
        }
    };
    Handler unitIdHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x123:
                    closeProgressDialog();
                    unitIdlists = (List<Map<String,Object>>) msg.obj;
                //    if (unitIdlists.size() != 0){
                        unitIdAdapter = new SimpleAdapter(MainActivity.this,unitIdlists,R.layout.unitid_item,new String[]{"sfdcser_name","deviceid","description"},new int[]{R.id.sfdcser_name,R.id.deviceid,R.id.description});
                        unitId.setAdapter(unitIdAdapter);
                /*   }else {
                        Toast.makeText(MainActivity.this,"Sorry, I can't find anything",Toast.LENGTH_LONG).show();
                        Log.i("哇","我什么都查不到");
                    }*/
                    break;
                default:
                    break;
            }
        }
    };

    Handler postHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x123:
                   try{
                       myApplication.setDeviceID(msg.obj.toString());
                   }catch (Exception e){

                   }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Login);
        setContentView(R.layout.activity_main);
        myApplication = (MyApplication) getApplication();
        PortalHost = (LinearLayout) findViewById(R.id.PortalHost);
        PlantCode = (LinearLayout) findViewById(R.id.PlantCode);
        Project = (LinearLayout) findViewById(R.id.Project);
        Station = (LinearLayout) findViewById(R.id.Station);
        UnitID = (LinearLayout) findViewById(R.id.UnitID);
        portalHost = (EditText) findViewById(R.id.portoal_host);
        plantCode = (EditText) findViewById(R.id.plant_code);
        project = (Spinner) findViewById(R.id.list_project);
        station = (Spinner) findViewById(R.id.list_station);
        unitId = (Spinner) findViewById(R.id.list_UnitId);
        work = (Spinner) findViewById(R.id.Work);
        go = (Button) findViewById(R.id.button_go);
        local = (EditText) findViewById(R.id.IP);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
                R.array.Work, android.R.layout.simple_spinner_item);
        work.setAdapter(adapter);
        plantCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH){
                    String[] getProject = {portalHost.getText().toString(),plantCode.getText().toString()};
                    myApplication.setPortalhost(portalHost.getText().toString());
                    myApplication.setPlantcode(plantCode.getText().toString());
                    // String[] getProject = {"172.26.100.226","E81"};
                    GetProjectAsynTask getProjectAsynTask = new GetProjectAsynTask(projectHandler);
                    getProjectAsynTask.execute(getProject);
                    showProgressDialog();
                }
                return false;
            }
        });

        project.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int arg0, long l) {
             //   Log.i("点击的选择",projectlists.get(arg0).get("siteCommunityId").toString());
                    String[] getStation = {portalHost.getText().toString(),projectlists.get(arg0).get("siteCommunityId").toString()};
                  //  app.setProject(projectlists.get(arg0).get("siteName").toString());
                     //   Log.i("SITE",""+getStation);
                        GetStationAsynTask getStationAsynTask = new GetStationAsynTask(stationHandler);
                        getStationAsynTask.execute(getStation);
                        showProgressDialog();

            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        station.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            //    Log.i("Station的选择是",""+stationlists.get(i).get("sfdcser_Id"));
              //  Log.i("Station的选择是",""+stationlists.get(i).get("serverid"));
                String[] getUnitId = {portalHost.getText().toString(),stationlists.get(i).get("serverid").toString()};
                GetUnitIdAsynTask getUnitIdAsynTask = new GetUnitIdAsynTask(unitIdHandler);
                getUnitIdAsynTask.execute(getUnitId);
                showProgressDialog();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Log.i("我是","null");
            }
        });

        unitId.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {


               // Log.i("数据",""+unitIdlists.get(i));
                  myApplication.setDeviceID(unitIdlists.get(i).get("deviceid").toString());

            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        work.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                final String ip = help.getIpAddressString() ;
                switch (arg2) {
                    case 0:
                        PortalHost.setVisibility(View.VISIBLE);
                        PlantCode.setVisibility(View.VISIBLE);
                        Project.setVisibility(View.VISIBLE);
                        Station.setVisibility(View.VISIBLE);
                        UnitID.setVisibility(View.VISIBLE);
                        local.setText("");
                        local.setEnabled(true);
                        go.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MainActivity.this , MasterActivity.class);
                                startActivity(intent);
                            }
                        });
                        break;
                    case 1:
                        local.setText(ip);
                        local.setEnabled(false);
                        PortalHost.setVisibility(View.INVISIBLE);
                        PlantCode.setVisibility(View.INVISIBLE);
                        Project.setVisibility(View.INVISIBLE);
                        Station.setVisibility(View.INVISIBLE);
                        UnitID.setVisibility(View.INVISIBLE);
                        go.setEnabled(true);
                        go.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(MainActivity.this , SlaveActivity.class);
                                startActivity(intent);

                            }
                        });
                        break;

                    default:
                        break;
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }

        });
        local.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_GO){
                    myApplication.setLocal(local.getText().toString());
                    Intent intent = new Intent(MainActivity.this , MasterActivity.class);
                    // intent.putExtra("服务器IP",master);
                    startActivity(intent);
                }
                return false;
            }
        });
    }
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Loading");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if(progressDialog != null){
            progressDialog.dismiss();
        }
    }

}

